package com.lizhi.dingdong.apk

import android.Manifest
import android.app.NotificationManager
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.viewmodel.compose.viewModel
import com.lizhi.dingdong.apk.data.NotificationItem
import com.lizhi.dingdong.apk.ui.NotificationScreen
import com.lizhi.dingdong.apk.ui.theme.Dingdong_apkTheme
import com.lizhi.dingdong.apk.viewmodel.NotificationViewModel

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestNotificationPermission()

        // 清除所有通知
        clearAllNotifications()

        enableEdgeToEdge()
        setContent {
            Dingdong_apkTheme {

                // 在这里初始化 ViewModel 和收集状态 (负责数据和生命周期)
                val viewModel: NotificationViewModel = viewModel()
                val notificationList by viewModel.uiState.collectAsState()

                NotificationScreen(notificationList)
            }
        }
    }

    fun requestNotificationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
                // 请求权限
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.POST_NOTIFICATIONS),
                    1001 // 自定义的请求码
                )
            }
        }
    }

    override fun onStart() {
        super.onStart()
        clearAllNotifications()
    }

    /**
     * 清除设备上所有由本应用发送的通知。
     */
    private fun clearAllNotifications() {
        // 1. 获取 NotificationManager 实例
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        // 2. 调用 cancelAll() 清除所有通知
        notificationManager.cancelAll()

        // 提示：此操作会清除通知栏中该 App 的所有通知，包括正在前台显示的（如果它不是前台服务通知）。
    }
}

@Preview(showBackground = true)
@Composable
fun NotificationScreenPreview() {

    val mockData = listOf(
        NotificationItem(0, "电信", "10/18", "标题1", "内容...", Color(0xFF2196F3).toArgb()),
        NotificationItem(1, "OPPO", "10/18", "标题2", null, Color(0xFF4CAF50).toArgb())
    )

    Dingdong_apkTheme {
        NotificationScreen(mockData)
    }
}